package com.kkb.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/welcome")
public class LastSignInServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("time".equals(cookie.getName())){
                response.getWriter().print("老朋友你好，上次访问时间为：" + cookie.getValue());
                createCookie(request, response);
                return ;
            }
        }
        response.getWriter().print("欢迎首次访问");
        createCookie(request, response);
    }

    private void createCookie(HttpServletRequest request, HttpServletResponse response) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        String time = simpleDateFormat.format(date);
        Cookie cookie = new Cookie("time",time);
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(60 * 60 * 24);

        response.addCookie(cookie);
    }
}
